package com.lml.controller;
import com.lml.dao.IUserDao;
import com.lml.entity.R;
import com.lml.entity.User;
import com.lml.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    private final IUserDao userDao;
    private final UserService userService;

    @Autowired
    public UserController(IUserDao userDao, UserService userService) {
        this.userDao = userDao;
        this.userService = userService;
    }
    @GetMapping("/{id}")
    public R get(@PathVariable(name = "id") Integer id) {
        System.out.println("查询用户ID：" + id);
        User user = userDao.findById(id);
        if (user == null) {
            return R.fail(404, "用户不存在");
        }
        return R.ok(user);
    }
    @PostMapping("/login")
    public R login(@RequestBody User user) {
        User loginUser = userDao.login(user.getUsername(), user.getPassword());
        if (loginUser == null) {
            return R.fail(401, "用户名或密码错误");
        }
        return R.ok(loginUser);
    }
    @PostMapping("/register")
    public R register(@RequestBody User user) {
        if (user.getUsername() == null || user.getPassword() == null) {
            return R.fail(211, "用户名或密码不能为空");
        }
        int result = userService.register(user);
        if (result == 201) {
            return R.fail(201, "用户名重复");
        }
        return R.ok(user);
    }

    @GetMapping("/list")
    public R findAll() {
        List<User> users = userDao.findAll();
        if (users == null || users.isEmpty()) {
            return R.fail(404, "没有找到任何用户");
        }
        return R.ok(users);
    }

    @PostMapping("/add")
    public R add(@RequestBody User user) {
        int result = userDao.add(user);
        if (result > 0) {
            return R.ok(user);
        }
        return R.fail(500, "添加用户失败");
    }

    @PutMapping("/update")
    public R update(@RequestBody User user) {
        int result = userDao.update(user);
        if (result > 0) {
            return R.ok(user);
        }
        return R.fail(500, "更新用户失败");
    }

    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable(name = "id") Integer id) {
        System.out.println("删除用户ID：" + id);
        int result = userDao.delete(id);
        if (result > 0) {
            return R.ok(id);
        }
        return R.fail(500, "删除用户失败");
    }
}
